<?php


namespace app\mall\controller;
use app\data\controller\api\Auth;
use app\mall\logic\walletLogic;
use app\mall_back\model\UserWalletModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;

class TurntablePrizes extends Auth
{
    /**
     * 转盘奖品
     */
   public function index(){
       $type = request()->get('type',0);
       $list = \app\data\model\TurntablePrizes::where(['type'=>$type,'status'=>1])
          ->select();
      return $list;
   }

    /**
     * 抽奖
     */
   public function lottery(){
       $type = request()->post('type',0);
       //判断类型
       if(!in_array($type,[0,1])){
           $this->error('抽奖失败');
       }
       $uId = $this->uuid;

       Db::startTrans();
       try{
           $redis = Cache::store('redis')->handler();
           $redis_key = "turntable_lottery" . '_' . $uId;
           $redis_key_info = $redis->get($redis_key);
           if ($redis_key_info) {
               $this->error("当前操作太快了,请等待");
           } else {
               $redis->set($redis_key, 1, 8);
           }

          //判断积分
          $userIntegral =  UserWalletModel::where(['u_id'=>$uId])->value('integral');
          if($type==0){
              $useIntegral = sysdata('turntable1_integral');
          }else{
              $useIntegral = sysdata('turntable2_integral');
          }
          if($useIntegral>$userIntegral){
              $this->error('您的积分不够');
          }
           $allIdArr = [];
           $list = \app\data\model\TurntablePrizes::field('id,probability')->where(['type'=>$type,'status'=>1])
               ->column('probability','id');
           foreach($list as $id=>$probability){
               $ids = array_fill(0,$probability,$id);
               $allIdArr = array_merge($allIdArr,$ids);
           }
          shuffle($allIdArr);
           $prizeId = $allIdArr[0];
          //扣除用户积分
           $res1 = walletLogic::wallet_detailed_add($uId, $useIntegral, 21, 2, 0, 'reduce','转盘抽奖');
           $res2 = Db::table('one_user_wallet')
               ->where('u_id', '=', $uId)
               ->dec('integral', $useIntegral)
               ->update();
           $prizeMoney = \app\data\model\TurntablePrizes::where(['id'=>$prizeId])->value('money');
           //增加用户夺宝币
           $res3 = walletLogic::wallet_detailed_add($uId, $prizeMoney, 22, 1, 0, 'add','转盘抽奖奖励');
           $res4 = Db::table('one_user_wallet')
               ->where('u_id', '=', $uId)
               ->inc('money', $prizeMoney)
               ->update();

        $redis->del($redis_key);
        Db::commit();
        $this->success('抽奖成功',$prizeId);

       }catch(Exception $e){
           Log::error($e->getMessage());
           Db::rollback();
       }

       $this->error('抽奖失败');

   }
}